package cn.wit.summit.chwan.ui.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.ApkVersionbean;
import cn.wit.summit.chwan.models.dto.CfgBean;
import cn.wit.summit.chwan.models.dto.CfgMain;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.dto.SurplusNumberBean;
import cn.wit.summit.chwan.models.dto.VersionDto;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.response.GetCommentTokenResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.ui.fragment.GameLibraryV2Fragment;
import cn.wit.summit.chwan.ui.fragment.MakeMoneyV3Fragment;
import cn.wit.summit.chwan.ui.fragment.PersonalV2Fragment;
import cn.wit.summit.chwan.ui.fragment.TodayRewardFragment;
import cn.wit.summit.chwan.ui.receiver.BroadcastAction;
import cn.wit.summit.chwan.ui.service.AppUpdataVersionService;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.DateUtils;
import cn.wit.summit.chwan.utils.DensityUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.JsonMapper;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PermissionManagerUtil;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.SystemInfoUtils;
import cn.wit.summit.chwan.widgets.VersionUpdataDialog;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/4/11.
 */

public class MainActivity extends MyActivity implements SensorEventListener {

    @Bind(R.id.mg_mian_fragmentlayout)
    FrameLayout mgMianFragmentlayout;
    @Bind(R.id.tabs_rg)
    RadioGroup tabsRg;
    @Bind(R.id.main_tip_iv)
    ImageView mainTipIv;
    @Bind(R.id.main_makemoney_tip_iv)
    ImageView mainMakemoneyTipIv;

    private FragmentManager fragmentManager;

//    private RecommendFragment recommendFragment;
//    private RecommendV2Fragment recommendV2Fragment;
    private TodayRewardFragment todayRewardFragment;
//    private FindFragment findFragment;
    private GameLibraryV2Fragment gameLibraryFragment;
    private MakeMoneyV3Fragment makeMoneyFragment;
    private PersonalV2Fragment personalFragment;
    private String recommendFragmentTag = "recommend";
    private String recommendFragmentV2Tag = "recommendv2";
//    private String findFragmentTag = "find";
    private String gameLibraryFragmentTag = "gamelib";
    private String makeMoneyFragmentTag = "makemoney";
    private String personalFragmentTag = "personal";
    private String todayRewardFragmentTag = "home";

    private int selectedPo = 0;
    private InstallAppRecver recver;

//    private Sensor mSensor;
//    private SensorManager mSensorManager;
//    private float mDegress;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;
    private Retrofit retrofitComment;
    private ApiUtil apiComment;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    public int getSelectedPo() {
        return selectedPo;
    }

    private boolean isSelectMakeMoney = false;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            selectedPo = 0;
        } else {
            selectedPo = bundle.getInt("MainPos");
        }
        switch (selectedPo) {
            case 0:
                tabsRg.check(R.id.tab_recommend);
                break;
            case 1:
                tabsRg.check(R.id.tab_find);
                break;
            case 2:
                isSelectMakeMoney = true;
                tabsRg.check(R.id.tab_makemoney);
                break;
            case 3:
                tabsRg.check(R.id.tab_my);
                break;
        }
    }

    public void changTab(int num) {
        switch (num) {
            case 0:
                tabsRg.check(R.id.tab_recommend);
                break;
            case 1:
                tabsRg.check(R.id.tab_find);
                break;
            case 2:
                isSelectMakeMoney = true;
                tabsRg.check(R.id.tab_makemoney);
                break;
            case 3:
                tabsRg.check(R.id.tab_my);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);
        retrofitComment = retrofitManager.getCommentRetrofit();
        apiComment = retrofitComment.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        Bundle bundle = this.getIntent().getExtras();
        if (bundle == null) {
            selectedPo = 0;
        } else {
            selectedPo = bundle.getInt("MainPos");

        }
        hideTitleBar();//隐藏默认基类title bar
        fragmentManager = this.getSupportFragmentManager();
        if (savedInstanceState != null) {
//            recommendFragment = (RecommendFragment) fragmentManager.findFragmentByTag(recommendFragmentTag);
//            recommendV2Fragment = (RecommendV2Fragment) fragmentManager.findFragmentByTag(recommendFragmentV2Tag);
//            findFragment = (FindFragment) fragmentManager.findFragmentByTag(findFragmentTag);
            gameLibraryFragment = (GameLibraryV2Fragment) fragmentManager.findFragmentByTag(gameLibraryFragmentTag);
            makeMoneyFragment = (MakeMoneyV3Fragment) fragmentManager.findFragmentByTag(makeMoneyFragmentTag);
            personalFragment = (PersonalV2Fragment) fragmentManager.findFragmentByTag(personalFragmentTag);
            todayRewardFragment = (TodayRewardFragment) fragmentManager.findFragmentByTag(todayRewardFragmentTag);
        }

        initBottomBar();
        selectionTab(selectedPo);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                checkVersion();
                getSurplusNumber();

                if (PermissionManagerUtil.hasStoragePermission(mContext))
                    initPath();

                //24小时还原一次数据
                if (System.currentTimeMillis() - PreferenceUtil.getLastUpdateGamePreferences(mContext) > 24 * 60 * 60 * 1000) {
                    getUpdateInfov2();
                }

                initSensor();
                getCommentToken();
            }
        }, 600);

        boolean isShareToGame = PreferenceUtil.getBoolPreferences(mContext, PreferenceUtil.PRE_SHARE_TO_GAME);
        if (!isShareToGame) {
            String shareGameId = getIntent().getStringExtra("shareGameId");
            if (!StringUtils.isEmpty(shareGameId) && !"0".equals(shareGameId)) {
                PreferenceUtil.saveBoolPreference(mContext, PreferenceUtil.PRE_SHARE_TO_GAME, true);
                IntentUtil.getInstance().goGamedetial(mAty, shareGameId);
            }
        }

        long isShowMakeMoneyTip = PreferenceUtil.getLongPreferences(mContext, PreferenceUtil.PRE_ISSHOW_MAKEMONEY_TIP);
        if (!DateUtils.isToday(isShowMakeMoneyTip)) {
//            showMakeMoneyTips();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void getCommentToken() {
        String comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
        if (!StringUtils.isEmpty(comentToken)) return;
        GetCommentTokenRequest tempRequest = retrofitManager.getCommentTokenRequest();
        apiComment.getCommentToken(tempRequest).enqueue(new MyCallback<ResponseBase<GetCommentTokenResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GetCommentTokenResponse> model) {
                GetCommentTokenResponse data = model.getData_info();
                String token = AESUtils.encrypt4Comment(data.getToken() + "|" + data.getTimes());
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, token);
                PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN_TIME, data.getTimes());
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
            }
        });
    }

    private void checkVersion() {
        api.getPlug(0).enqueue(new MyCallback<ResponseBase<CfgMain>>() {
            @Override
            public void onSuccess(ResponseBase<CfgMain> model) {
                CfgMain data = model.getData_info();
                if (data != null) {
                    try {
                        CfgBean cfgBean = data.getCfg();
                        String cfgS = JsonMapper.getInstance().toJson(cfgBean);
                        PreferenceUtil.saveNergyUrlPreference(getApplicationContext(), cfgS);
                        MyApplication.cfgPlug = cfgBean;
                        MyApplication.arrayCommentExplain = data.getCfg().getArray_comment_explain();
                        MyApplication.arrayUploadExplain = data.getCfg().getArray_upload_explain();
                        ApkVersionbean apkVersionbeanApp = data.getApp();


                        String[] version = SystemInfoUtils.getInstance(MainActivity.this).getVersionNameArray();
                        String nVersion = apkVersionbeanApp.getVer();

                        // 新版本大版本号
                        int nCode = Integer.parseInt(nVersion.split("_")[0]);
                        // 最低版本要求
                        String compatible = apkVersionbeanApp.getVer_compatible();
                        int cCode = Integer.parseInt(compatible.split("_")[0]);
                        if (Integer.parseInt(version[0]) <= nCode) {
                            VersionDto versionDto = new VersionDto();
                            versionDto.setSize(apkVersionbeanApp.getSize() + "M");
                            versionDto.setVersionName("v " + nVersion.split("_")[1]);
                            versionDto.setAndroidUrl(apkVersionbeanApp.getDown_url());
                            versionDto.setVersionNo(Integer.parseInt(nVersion.split("_")[0]));
                            versionDto.setInfo(apkVersionbeanApp.getVer_info());
                            versionDto.setHead_pic(apkVersionbeanApp.getHead_pic());
                            versionDto.setTow_tpl_back_ground_pic(apkVersionbeanApp.getTow_tpl_back_ground_pic());
                            versionDto.setTpl_type(apkVersionbeanApp.getTpl_type());
                            if (Integer.parseInt(version[0]) < nCode) {// 小于大版本号,再判断是否小要强制升级
                                // 判断是否要强制升级
                                if (Float.parseFloat(version[0]) < cCode) {
                                    updataAppVersion(versionDto, true);
                                } else {
                                    updataAppVersion(versionDto, false);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
            }
        });
    }

    private void initSensor() {
        // 取传感器
//        try {
//            mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
//            mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI);
//        } catch (Exception e) {
//            LogUtils.e(e.getMessage());
//        }
    }

    private void updataAppVersion(final VersionDto versionDto, final boolean isMust) {
        final VersionUpdataDialog dialog = new VersionUpdataDialog(mContext);
        dialog.show();
        dialog.setTitle(getResources().getString(R.string.updata_dialog_title_str));
        dialog.setVersion(versionDto.getVersionName());
        dialog.setSize(versionDto.getSize());
        dialog.setMsg(versionDto.getInfo());
        if (isMust)
            dialog.setMustUpdate();
        dialog.setCancleBtn(getResources().getString(R.string.updata_dialog_ok_str), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean hasStoragePermiss = PermissionManagerUtil.hasStoragePermission(mContext);
                boolean haveInstallPermission = false;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //先获取是否有安装未知来源应用的权限
                    haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                    haveInstallPermission = true;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (EasyPermissions.hasPermissions(mContext, Manifest.permission.REQUEST_INSTALL_PACKAGES)) {
                        haveInstallPermission = true;
                    }
                } else {
                    haveInstallPermission = true;
                }
                if (hasStoragePermiss && haveInstallPermission) {//有内存卡权限
                    initPath();
                    Intent intent = new Intent(mContext, AppUpdataVersionService.class);
                    intent.putExtra("data", versionDto);
                    startService(intent);
                    showToast("正在下载更新！");
                    if (!isMust)
                        dialog.dismiss();
                } else {//没有内存卡权限
                    if (!hasStoragePermiss) {
                        Intent intent = new Intent(BroadcastAction.ACTION_CHECKANDREQUEST_PERMISS);
                        intent.putExtra("permisson", PermissionManagerUtil.PERM_STORAGE);
                        sendBroadcast(intent);
                    }
                    if (!haveInstallPermission) {
                        Intent intent = new Intent(BroadcastAction.ACTION_INSTALL_APK);
                        intent.putExtra("permisson", PermissionManagerUtil.PERM_INSTALL);
                        sendBroadcast(intent);
                    }
                }
            }
        });
        if (!isMust) {
            dialog.setBtn(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }
    }

    private void getUpdateInfov2() {

        if (NetWorkUtils.isNetworkConnected(this)) {
            final List<APKUtils.APKInfo> apkInfos = APKUtils.getInstance(this).getAllInstallApkInfo(this);

            Iterator<APKUtils.APKInfo> iterator = apkInfos.iterator();
            StringBuffer buffer = new StringBuffer();
//            List<String> apkPackages = new ArrayList<>();
            while (iterator.hasNext()) {
                APKUtils.APKInfo apkInfo = iterator.next();
                buffer.append(",");
                buffer.append(apkInfo.getPackageName());

            }
            String packagenames = buffer.toString();
            packagenames = packagenames.replaceFirst(",", "");
            try {
                api.getbackAllGameVersion(packagenames).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
                    @Override
                    public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                        List<GameListBaseBean> data = model.getData_info();
                        if (data != null && data.size() > 0) {
                            Iterator<GameListBaseBean> gaIterator = data.iterator();
                            while (gaIterator.hasNext()) {
                                GameListBaseBean gameListBaseBean = gaIterator.next();
                                Iterator<APKUtils.APKInfo> iteratorV2 = apkInfos.iterator();
                                while (iteratorV2.hasNext()) {
                                    APKUtils.APKInfo apkInfo = iteratorV2.next();
                                    if (apkInfo.getPackageName().equals(gameListBaseBean.getGame_package_name())) {
                                        DownLoadTaskTable table = DownloadTaskManager.getInstance().findByGameId(gameListBaseBean.getGame_id());
                                        if (table != null) {

                                        } else {
                                            table = gameListBaseBean.getDownloadTaskTableSimple();
                                            table.setVer(apkInfo.getVersionCode());
                                            table.setDownStatus(DownLoadStatusConfig.INSTALLED);
                                            DownloadTaskManager.getInstance().insertDownload(table);
                                        }
                                        iteratorV2.remove();
                                        break;
                                    }
                                }
                            }


                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

    private void showTips() {

        Display display = getWindowManager().getDefaultDisplay();
        int margin = DensityUtil.dp2px(mContext, 15);

        int leftM = display.getWidth() * 7 / 8;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                , ViewGroup.LayoutParams.WRAP_CONTENT);
        params.leftMargin = leftM + margin;
        params.topMargin = margin / 2;
        mainTipIv.setLayoutParams(params);
        mainTipIv.setVisibility(View.VISIBLE);
    }

    private void showMakeMoneyTips() {

        Display display = getWindowManager().getDefaultDisplay();
        int margin = DensityUtil.dp2px(mContext, 15);

        int leftM = display.getWidth() * 5 / 8;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                , ViewGroup.LayoutParams.WRAP_CONTENT);
        params.leftMargin = leftM + margin;
        params.topMargin = margin / 2;
        mainMakemoneyTipIv.setLayoutParams(params);
        mainMakemoneyTipIv.setVisibility(View.VISIBLE);
    }

    private void hideTips() {
        mainTipIv.setVisibility(View.GONE);
    }

    private void initBottomBar() {
        tabsRg = (RadioGroup) findViewById(R.id.tabs_rg);
        tabsRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.tab_recommend:
                        selectionTab(0);
                        break;
                    case R.id.tab_find:
                        selectionTab(1);
                        break;
                    case R.id.tab_makemoney:
                        selectionTab(2);
                        break;
                    case R.id.tab_my:
                        selectionTab(3);
                        break;
                }
            }
        });
        recver = new InstallAppRecver();
        IntentFilter filter = new IntentFilter();
//        filter.addAction(BroadcastAction.ACTION_INSTALL_OBB_DATA_APK);
        filter.addAction("com.send.message.hasClickPrase");
//        filter.addAction("com.send.message.showNotWifitodown");
        registerReceiver(recver, filter);

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
//        if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
//            float degree = sensorEvent.values[2];
//            if (Math.abs(degree - mDegress) <= 2) return;
//            EventBus.getDefault().post(new SensorChangedEvent(degree));
//            mDegress = degree;
//        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    class InstallAppRecver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, Intent intent) {
            if (intent.getAction().equals("com.send.message.hasClickPrase")) {
                surplusNumberBean.setPraise_surplus_number(0);
            } else if (intent.getAction().equals("com.send.message.showNotWifitodown")) {

            } else {

            }
        }
    }

    //private void s
    private void selectionTab(int position) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction);
        selectedPo = position;

        switch (position) {
            case 0://推荐
//                getBarHeightIv().setVisibility(View.VISIBLE);
//                getBarHeightIv().setBackgroundResource(R.drawable.header_gradient_bg);
//                if (recommendFragment == null) {
//                    recommendFragment = new RecommendFragment();
//                    transaction.add(R.id.mg_mian_fragmentlayout, recommendFragment, recommendFragmentTag);
//                } else {
//                    transaction.show(recommendFragment);
//                }


//                if (recommendV2Fragment == null) {
//                    recommendV2Fragment = new RecommendV2Fragment();
//                    transaction.add(R.id.mg_mian_fragmentlayout, recommendV2Fragment, recommendFragmentV2Tag);
//                } else {
//                    transaction.show(recommendV2Fragment);
//                }

                if (todayRewardFragment == null) {
                    todayRewardFragment = new TodayRewardFragment();
                    transaction.add(R.id.mg_mian_fragmentlayout, todayRewardFragment, todayRewardFragmentTag);
                } else {
                    transaction.show(todayRewardFragment);
                }
                StatFactory.getInstance().sendClickPage(mContext, "Index", "Index");
                break;
            case 1://发现
//                getBarHeightIv().setVisibility(View.VISIBLE);
//                getBarHeightIv().setBackgroundResource(R.drawable.header_gradient_bg);
//                if (findFragment == null) {
//                    findFragment = new FindFragment();
//                    transaction.add(R.id.mg_mian_fragmentlayout, findFragment, findFragmentTag);
//                } else {
//                    transaction.show(findFragment);
//                }

                if (gameLibraryFragment == null) {
                    gameLibraryFragment = new GameLibraryV2Fragment();
                    transaction.add(R.id.mg_mian_fragmentlayout, gameLibraryFragment, gameLibraryFragmentTag);
                } else {
                    transaction.show(gameLibraryFragment);
                }
                break;
            case 2://赚钱
                PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_ISSHOW_MAKEMONEY_TIP, System.currentTimeMillis());
                mainMakemoneyTipIv.setVisibility(View.GONE);
//                getBarHeightIv().setVisibility(View.GONE);
//                getBarHeightIv().setBackgroundResource(R.drawable.header_gradient_bg);

                if (makeMoneyFragment == null) {
                    makeMoneyFragment = new MakeMoneyV3Fragment();
                    transaction.add(R.id.mg_mian_fragmentlayout, makeMoneyFragment, makeMoneyFragmentTag);
                } else {
                    if (isSelectMakeMoney)
                        makeMoneyFragment.setSelectIndex();
                    transaction.show(makeMoneyFragment);
                }
                showDialog();
                break;
            case 3://我的
                hideTips();
//                getBarHeightIv().setVisibility(View.VISIBLE);
//                getBarHeightIv().setBackgroundResource(R.drawable.header_gradient_v2_bg);
//                getBarHeightIv().setVisibility(View.GONE);
                if (personalFragment == null) {
                    personalFragment = new PersonalV2Fragment();
                    transaction.add(R.id.mg_mian_fragmentlayout, personalFragment, personalFragmentTag);
                } else {
                    transaction.show(personalFragment);
                }
                break;
        }

        try {
            transaction.commit();
        } catch (Exception e) {

        }
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (gameLibraryFragment != null) {
            transaction.hide(gameLibraryFragment);
        }
        if (personalFragment != null) {
            transaction.hide(personalFragment);
        }
        if (makeMoneyFragment != null) {
            transaction.hide(makeMoneyFragment);
        }
        if (todayRewardFragment != null) {
            transaction.hide(todayRewardFragment);
        }
    }

    @Override
    protected void onDestroy() {
        stopService(new Intent(mContext, AppUpdataVersionService.class));
//        if (mSensorManager != null)
//            mSensorManager.unregisterListener(this);
        super.onDestroy();
        if (recver != null)
            unregisterReceiver(recver);
    }

    @Override
    protected void onResume() {
//        if (isShowSlash) {
//            isShowSlash = false;
//            startActivity(new Intent(mContext, SplashActivity.class));
//        }
        super.onResume();

//        if (mSensorManager != null && mSensor != null)
//            mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI); //rate suitable for the user interface
//        SharedPreferences sp = MyApplication.getMyApplication().getRedps();
//        if (sp.getBoolean("isclose", false) == true) {
//            Log.e("TAG", "MainOnResume");
//            RedEnvelopeUtils.ShowRedEnvelope(MainActivity.this);
//        }
        getUserinfo();

    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(this)) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);

                                if (data.getDefaultNickname() == 0 || data.getAvatar().contains("avatar_default")) {//未设置昵称
                                    showToast(getResources().getString(R.string.set_persoanl_info_dialog_msg_str));
                                    Intent intent = new Intent(mContext, SetPersonalInformationActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("login_data", data);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(mAty);
                            }
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 10) {
            if (taskTable != null) {
                APKUtils.getInstance(mContext).installAPK(mContext, taskTable.getDownPath(), taskTable.getGameId());
            }
        } else if (requestCode == 11) {
            if (EasyPermissions.somePermissionPermanentlyDenied(this, Arrays.asList(permissions))) {
                new AppSettingsDialog.Builder(this).setTitle("注意").setRationale("下载游戏须要读写存储权限请授权").build().show();
            }
//            else if (!EasyPermissions.hasPermissions(this,permissions)){
//                ActivityCompat.requestPermissions(this,
//                        permissions,
//                        requestCode);
////                EasyPermissions.requestPermissions(
////                        this,
////                        getString(R.string.rationale_init_storage_contacts),
////                        PermissionManagerUtil.RC_STORAGE_PERM,
////                        PermissionManagerUtil.PERM_STORAGE);
//            }
        }
    }

    private DownLoadTaskTable taskTable = null;


    public SurplusNumberBean surplusNumberBean;

    private void getSurplusNumber() {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            try {
                int uid = AccountUtil.getInstance().getUid();
                String token = AccountUtil.getInstance().getToken();
                api.getSurplusNumber(uid, token).enqueue(new MyCallback<ResponseBase<SurplusNumberBean>>() {
                    @Override
                    public void onSuccess(ResponseBase<SurplusNumberBean> model) {
                        SurplusNumberBean data = model.getData_info();
                        if (data != null) {
                            surplusNumberBean = data;
                            int showNumber = data.getNotice_surplus_number() + data.getReplay_surplus_number();
                            if (showNumber > 0 || data.getPraise_surplus_number() > 0) {
                                showTips();//现实红点
                            }
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

    public void showDialog() {
        long nowTime = PreferenceUtil.getLongPreferences(mContext, PreferenceUtil.PRE_FIRST_START_APP);
        AccountBean mAccountBean = AccountUtil.getInstance().getAccountData();
        if (!DateUtils.isToday(nowTime) && (
                (mAccountBean==null) || (mAccountBean!=null && mAccountBean.getRunAppMoney()>0))) {
//            MessageMoneyDialog mMessageMoneyDialog = new MessageMoneyDialog(mContext);
//            mMessageMoneyDialog.show();
//            mMessageMoneyDialog.setShowType(3);
        }
    }
}
